package world.ztomorrow.author.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import world.ztomorrow.author.dao.mapper.AuthorInfoMapper;
import world.ztomorrow.author.dao.po.AuthorInfo;
import world.ztomorrow.author.dto.AuthorInfoDto;
import world.ztomorrow.author.dto.resp.AuthorRegisterReqDto;
import world.ztomorrow.author.service.AuthorService;
import world.ztomorrow.common.dto.RestResp;

import java.time.LocalDateTime;
import java.util.Objects;


@Service
@RequiredArgsConstructor
public class AuthorServiceImpl implements AuthorService {

    private final AuthorInfoMapper authorInfoMapper;

    @Override
    public RestResp<Integer> getStatus(Long userId) {
        AuthorInfoDto author = this.getAuthor(userId);
        return RestResp.ok(author == null ? null : author.getStatus());
    }

    @Override
    public RestResp<Void> register(AuthorRegisterReqDto dto) {
        // 校验该用户是否已注册为作家
        AuthorInfoDto author = this.getAuthor(dto.getUserId());
        if (Objects.nonNull(author)) {
            // 该用户已经是作家，直接返回
            return RestResp.ok();
        }
        // 保存作家注册信息
        AuthorInfo authorInfo = BeanUtil.copyProperties(dto, AuthorInfo.class);
        authorInfo.setInviteCode("0");
        authorInfo.setCreateTime(LocalDateTime.now());
        authorInfo.setUpdateTime(LocalDateTime.now());
        authorInfoMapper.insert(authorInfo);
        return RestResp.ok();
    }

    public AuthorInfoDto getAuthor(Long userId) {
        AuthorInfo authorInfo = new LambdaQueryChainWrapper<>(authorInfoMapper)
                .eq(AuthorInfo::getUserId, userId)
                .one();
        return authorInfo == null ? null : BeanUtil.copyProperties(authorInfo, AuthorInfoDto.class);
    }

}
